package com.explorati.LeetCode22.getKthFromEnd;

/**
 * @ Author : Weijian_Wang
 * @ Date : Created in 18:39 2020/9/13 0013
 * @ Description ：
 */
public class Solution1 {
    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    /**
     * 给定一个链表: 1->2->3->4->5, 和 k = 2.
     * 返回链表 4->5.
     * @param head
     * @param k
     * @return
     */
    public ListNode getKthFromEnd(ListNode head, int k) {
       //双指针解法
        ListNode pre = head;
        //end末指针，pre和end相差固定为k
        ListNode end = head;
        while(k > 0) {
            end = end.next;
            k --;
        }

        while(end != null) {
            pre = pre.next;
            end = end.next;
        }
        return pre;
    }
}
